package org.example.order.controller;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.example.order.VO.LoginVO;
import org.example.order.VO.RegisterVO;
import org.example.order.VO.UserVO;
import org.example.order.common.APIResponse;
import org.example.order.common.ResponseCode;
import org.example.order.entity.Admin;
import org.example.order.entity.User;

import org.example.order.permission.Access;
import org.example.order.permission.AccessLevel;
import org.example.order.service.impl.UserServiceImpl;
import org.example.order.util.IpUtil;
import org.example.order.util.JWTUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/User")
public class UserController {
    @Resource
    private UserServiceImpl userService;
    @GetMapping("/selectById/{id}")
    public APIResponse<User> getUserById(@PathVariable Long id){
        User user=userService.selectById(id);
        if(user==null){
            return new APIResponse<>(ResponseCode.FAIL,"用户不存在");
        }
        return new APIResponse<>(ResponseCode.SUCCESS, "查询成功", user);
    }
    @GetMapping("/selectPage")
    public APIResponse<PageInfo<User>> getUserPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                                   @RequestParam(defaultValue = "10") Integer pageSize,
                                                   @RequestParam(required = false) String keyword) {
        // 使用 try-with-resources 确保 Page 资源被正确关闭
        try (Page<Object> page = PageHelper.startPage(pageNum, pageSize)) {
            // 调用修改后的 service 方法获取数据列表
            List<User> userList = userService.getUserList(keyword);

            // 将结果封装到 PageInfo 对象
            PageInfo<User> pageInfo = new PageInfo<>(userList);

            return new APIResponse<>(ResponseCode.SUCCESS, "查询成功", pageInfo);
        }
    }
    @PostMapping("/register")
    public APIResponse<User> register(@RequestBody @Valid RegisterVO registerVO){

        User user=userService.register(registerVO);
        return new APIResponse<>(ResponseCode.SUCCESS,"注册成功",user);
    }
    @PostMapping("/login")
    public APIResponse<Map<String, Object>> login(@RequestBody @Valid LoginVO loginVO, HttpServletRequest request){
        String ip= IpUtil.getIpAddr(request);
        UserVO userVO =userService.login(loginVO,ip);
        Map<String, Object> map=new HashMap<>();
        map.put("token",userVO.getToken());
        map.put("userInfo",userVO);
        return new APIResponse<>(ResponseCode.SUCCESS,"登录成功",map);
    }
    @GetMapping("info")
    public APIResponse<User> getInfo(HttpServletRequest request){
        String token=request.getHeader("Authorization");
        System.out.println(request.getHeader("Authorization"));
        log.info("当前token为：[{}]",token);
        try {
            // 验证令牌
            DecodedJWT verify = JWTUtils.verify(token);
            Map<String, String> map=JWTUtils.getTokenData(token);
            log.info(map.get("id"));
            User user=userService.getById(map.get("id"));
            return new APIResponse<>(ResponseCode.SUCCESS,"请求成功",user);
        } catch (SignatureVerificationException e) {
            log.error(e.getMessage());
            return new APIResponse<>(ResponseCode.FAIL,"无效签名");
        }catch (TokenExpiredException e){
            log.error(e.getMessage());
            return new APIResponse<>(ResponseCode.FAIL,"token过期");
        }catch (AlgorithmMismatchException e){
            log.error(e.getMessage());
            return new APIResponse<>(ResponseCode.FAIL,"算法不一致");

        }catch (Exception e){
            log.error(e.getMessage());
            return new APIResponse<>(ResponseCode.FAIL,"token无效！");
        }
    }
    @PutMapping("/update")
    public APIResponse<String> updateUserInfo(@RequestBody @Valid UserVO User){
        String res=userService.updateUserInfo(User);
        if (res.equals("修改成功"))
            return new APIResponse<>(ResponseCode.SUCCESS,"成功修改",res);
        else return new APIResponse<>(ResponseCode.FAIL,"修改失败",res);
    }
    @PutMapping("/changePassword")
    public APIResponse<Boolean> updatePassword(@RequestParam Long userId,@RequestParam String oldPassword,@RequestParam String newPassword){
        if(newPassword.length()>20||newPassword.length()<6){
            return new APIResponse<>(ResponseCode.FAIL,"新密码格式错误");
        }
        boolean res=userService.updatePassword(userId,oldPassword,newPassword);
        return new APIResponse<>(ResponseCode.SUCCESS,"修改成功",res);
    }
    @Access(level = AccessLevel.ADMIN)
    @PostMapping("/add")
    public APIResponse<User> add(@RequestBody User user) {
        return new APIResponse<>(ResponseCode.FAIL," 暂时不允许增加用户",user);
//        userService.add(user);
//        return new APIResponse(ResponseCode.SUCCESS, "添加成功");
    }
    /**
     * 删除用户（逻辑删除）
     * 用户主动删除
     */
    @DeleteMapping("{id}/cancel")
    public APIResponse<Boolean> cancelAccount(@PathVariable Long id, HttpServletRequest request) {
        // 获取并验证用户令牌
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            return new APIResponse<>(ResponseCode.UNAUTHORIZED, "请提供有效的授权令牌", false);
        }

        // 获取用户信息
        UserVO userVO = userService.getUserInfoByToken(token);
        if (userVO == null) {
            return new APIResponse<>(ResponseCode.UNAUTHORIZED, "无效的用户令牌或会话已过期", false);
        }

        // 验证用户身份
        if (!userVO.getId().equals(id)) {
            return new APIResponse<>(ResponseCode.FORBIDDEN, "权限不足：只能注销自己的账号", false);
        }

        // 执行账号注销
        try {
            boolean res = userService.removeUser(id);
            if (!res) {
                return new APIResponse<>(ResponseCode.FAIL, "账号注销失败，请稍后重试", false);
            }
            return new APIResponse<>(ResponseCode.SUCCESS, "账号已成功注销", true);
        } catch (Exception e) {
            log.error("用户注销失败: " + id, e);
            return new APIResponse<>(ResponseCode.INTERNAL_SERVER_ERROR, "系统错误: " + e.getMessage(), false);
        }
    }
    /**
     * 删除用户（逻辑删除）
     */
    @Access(level = AccessLevel.ADMIN)
    @DeleteMapping("/{id}")
    public APIResponse<Boolean> removeUser(@PathVariable Long id) {
        boolean result = userService.removeUser(id);
        return new APIResponse<>(ResponseCode.SUCCESS,"删除成功",result);
    }

    /**
     * 批量删除用户（逻辑删除）
     */
    @Access(level = AccessLevel.ADMIN)
    @DeleteMapping("/batch")
    public APIResponse<Boolean> removeUserBatch(@RequestBody List<Long> ids) {
        boolean result = userService.removeUserBatch(ids);
        return new APIResponse<>(ResponseCode.SUCCESS,"修改成功",result);
    }

    /**
     * 恢复用户
     */
    @Access(level = AccessLevel.ADMIN)
    @PutMapping("/restore/{id}")
    public APIResponse<Boolean> restoreUser(@PathVariable Long id) {
        boolean result = userService.restoreUser(id);
        return new APIResponse<>(ResponseCode.SUCCESS,"修改成功",result);
    }

    /**
     * 批量恢复用户
     */
    @Access(level = AccessLevel.ADMIN)
    @PutMapping("/restore/batch")
    public APIResponse<Boolean> restoreUserBatch(@RequestBody List<Long> ids) {
        boolean result = userService.restoreUserBatch(ids);
        return new APIResponse<>(ResponseCode.SUCCESS,"修改成功",result);
    }
    @Access(level = AccessLevel.ADMIN)
    @GetMapping("/selectAll")
    public APIResponse<List<User>> selectAll() {
        List<User> list = userService.selectAll();
        return new APIResponse<>(ResponseCode.SUCCESS, "查询成功", list);
    }
    @PostMapping("/test")
    public APIResponse test(String token){
        log.info("当前token为：[{}]",token);
        try {
            // 验证令牌
            DecodedJWT verify = JWTUtils.verify(token);
            Map<String, String> map=JWTUtils.getTokenData(token);
            return new APIResponse<>(ResponseCode.SUCCESS,"请求成功",map);
        } catch (SignatureVerificationException e) {
            log.error(e.getMessage());
            return new APIResponse<>(ResponseCode.FAIL,"无效签名",false);
        }catch (TokenExpiredException e){
            log.error(e.getMessage());
            return new APIResponse<>(ResponseCode.FAIL,"token过期",false);
        }catch (AlgorithmMismatchException e){
            log.error(e.getMessage());
            return new APIResponse<>(ResponseCode.FAIL,"算法不一致",false);

        }catch (Exception e){
            log.error(e.getMessage());
            return new APIResponse<>(ResponseCode.FAIL,"token无效！",false);
        }
    }
}
